package com.hadluo.qq.server.service.impl;

import com.hadluo.qq.server.entity.Group;
import com.hadluo.qq.server.entity.GroupMember;
import com.hadluo.qq.server.mapper.GroupMemberMapper;
import com.hadluo.qq.server.mapper.GroupMapper;
import com.hadluo.qq.server.service.GroupService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;
import java.util.Random;

@Service
public class GroupServiceImpl implements GroupService {

    @Autowired
    private GroupMapper groupMapper;

    @Autowired
    private GroupMemberMapper groupMemberMapper;

    @Override
    @Transactional
    public Group createGroup(Group group, Long ownerUserId, List<Long> memberUserIds) {
        // 生成群号
        String groupNumber;
        do {
            groupNumber = generateGroupNumber();
        } while (groupMapper.existsByGroupNumber(groupNumber));

        // 设置群组基本信息
        group.setGroupNumber(groupNumber);
        group.setOwnerId(ownerUserId);
        group.setCreateTime(new Date());
        groupMapper.save(group);

        // 添加群主为群成员
        GroupMember ownerMember = new GroupMember();
        ownerMember.setGroupId(group.getId());
        ownerMember.setUserId(ownerUserId);
        ownerMember.setRole(2); // 群主角色
        ownerMember.setJoinTime(new Date());
        groupMemberMapper.save(ownerMember);

        // 添加其他成员
        for (Long userId : memberUserIds) {
            if (!userId.equals(ownerUserId)) {
                GroupMember member = new GroupMember();
                member.setGroupId(group.getId());
                member.setUserId(userId);
                member.setRole(0); // 普通成员角色
                member.setJoinTime(new Date());
                groupMemberMapper.save(member);
            }
        }

        return group;
    }

    @Override
    public List<Group> getUserGroups(Long userId) {
        return groupMapper.findGroupsByUserId(userId);
    }

    @Override
    public List<GroupMember> getGroupMembers(Long groupId) {
        return groupMemberMapper.findByGroupId(groupId);
    }

    @Override
    @Transactional
    public void addGroupMembers(Long groupId, List<Long> userIds) {
        for (Long userId : userIds) {
            if (!groupMemberMapper.existsByGroupIdAndUserId(groupId, userId)) {
                GroupMember member = new GroupMember();
                member.setGroupId(groupId);
                member.setUserId(userId);
                member.setRole(0); // 普通成员角色
                member.setJoinTime(new Date());
                groupMemberMapper.save(member);
            }
        }
    }

    @Override
    @Transactional
    public void removeGroupMember(Long groupId, Long userId) {
        GroupMember member = groupMemberMapper.findByGroupIdAndUserId(groupId, userId);
        if (member != null) {
            groupMemberMapper.delete(member);
        }
    }

    @Override
    @Transactional
    public Group updateGroup(Group group) {
        groupMapper.update(group);
        return group;
    }

    @Override
    @Transactional
    public void dissolveGroup(Long groupId, Long operatorUserId) {
        Group group = groupMapper.findById(groupId).orElse(null);
        if (group != null && group.getOwnerId().equals(operatorUserId)) {
            // 删除所有群成员
            groupMemberMapper.deleteByGroupId(groupId);
            // 删除群组
            groupMapper.delete(groupId);
        }
    }

    @Override
    @Transactional
    public void updateMemberRole(Long groupId, Long userId, Integer role) {
        GroupMember member = groupMemberMapper.findByGroupIdAndUserId(groupId, userId);
        if (member != null) {
            member.setRole(role);
            groupMemberMapper.save(member);
        }
    }

    @Override
    @Transactional
    public void updateMemberAlias(Long groupId, Long userId, String alias) {
        GroupMember member = groupMemberMapper.findByGroupIdAndUserId(groupId, userId);
        if (member != null) {
            member.setAlias(alias);
            groupMemberMapper.save(member);
        }
    }

    @Override
    public List<Group> searchGroups(String keyword) {
        return groupMapper.searchGroups(keyword);
    }

    @Override
    public Group getGroupById(Long groupId) {
        return groupMapper.findById(groupId).orElse(null);
    }

    @Override
    public Group getGroupByNumber(String groupNumber) {
        return groupMapper.findByGroupNumber(groupNumber).orElse(null);
    }

    @Override
    @Transactional
    public void updateGroupLastMessage(Long groupId, String lastMessage, Long lastMessageTime) {
        Group group = groupMapper.findById(groupId).orElse(null);
        if (group != null) {
            group.setLastMessage(lastMessage);
            group.setLastMessageTime(lastMessageTime);
            groupMapper.update(group);
        }
    }

    /**
     * 生成群号
     * @return 9位随机数字字符串
     */
    private String generateGroupNumber() {
        Random random = new Random();
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < 9; i++) {
            sb.append(random.nextInt(10));
        }
        return sb.toString();
    }
}